//Global.cs

using UnityEngine;
using System.Reflection;
using FairyGUI;
using System.IO;

public class Global : MonoBehaviour {
    void SetStreamingAssetsLoader()
    {
        FieldInfo field = typeof(UIPackage).GetField("_loadFromResourcesPath",
            BindingFlags.NonPublic | BindingFlags.Static);

        if (field != null)
        {
            UIPackage.LoadResource newLoader = (string name, string extension, System.Type type, out DestroyMethod destroyMethod) =>
            {
                destroyMethod = DestroyMethod.Unload;
                string filePath = Path.Combine(Application.streamingAssetsPath, name + extension);
                try
                {
#if UNITY_EDITOR
                    return Resources.Load(name, type);
#else
                    //运行环境使用AB包加载资源
                    string newName = name.Replace("FairyGUI/", "");
                    return ABMgr.GetInstance().LoadRes("fairyres", newName, type);
#endif
                }
                catch (System.Exception e)
                {
                    Debug.LogError($"Failed to load FairyGUI resource {filePath}: {e.Message}");
                    return null;
                }
            };
            field.SetValue(null, newLoader);
        }
    }


    // Use this for initialization
    void Awake()
    {
        Application.runInBackground = true;
        SetStreamingAssetsLoader();
    }

    // Use this for initialization
    void Start()
    {
        // 获取启动参数（包括程序名本身）
        string[] args = System.Environment.GetCommandLineArgs();
        if (args.Length >= 2) {
            Debug.Log("Parameter: " + args[1]);
            XluaManager.Init(args[1]);
        }
    }



    // Update is called once per frame
    void Update () {
        XluaManager.Lua.DoString("Update()");
    }

    void OnDestroy() {
    }
}